import axios from 'axios'
import { MessageBox, Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000
})
// request interceptor
service.interceptors.request.use(
  config => {
    config.headers['Access-Token'] = localStorage.getItem('access_token') || ''
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */
  response => {
    const res = response.data

    if (res.code !== 0) {
      if (res.code === 100003) {
        return res
      }
      if (res.message === '版本号已存在') {
        Message({
          message: res.message,
          type: 'error'
        })
      }
      if (res.code === 1017) { // 登录错误
        Message({
          message: res.message,
          type: 'error'
        })
      }
      if (res.code === 1015) { // token失效  expired
        console.log('token失效  expired:')
        // location.reload()
      }
      console.log('res.message:', res.message)
      return Promise.reject(new Error(res.message || 'Error'))
      
    } else {
      return res
    }
  },
  error => {
    console.log('error.response', error.response)
    // const err = error.response.data
    if (error.response.data.code === 4031001) { // token失效  expired
      console.log('process.env.VUE_APP_ENV >>>>>' + process.env.VUE_APP_ENV)
      if (process.env.VUE_APP_ENV === 'production') {
        MessageBox.confirm('身份验证失效，请重新进入', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          console.log('==============token expired==============')
        })
      } else {
        MessageBox.confirm('身份验证失效', '提示', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

        })
      }
    }
    return Promise.reject(err)
  }
)
export default service
